﻿using System;
using System.Linq;
using System.Globalization;
using System.Security.Principal;
using System.Web.Mvc;
using System.Web.Security;
using Ext.Net.MVC;
using System.Web.UI.MobileControls;
using System.Collections.Generic;
using Ext.Net;
using Buffalo.Lib.Common;
using Buffalo.Administration.DAL;

namespace Buffalo.Web.Areas.Tourism.Controllers
{
    [HandleError]
    public class MemberController : Controller
    {
        // This constructor is used by the MVC framework to instantiate the controller using
        // the default forms authentication and membership providers.
        public MemberController() : this(null, null) { }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments at the end of this file for more
        // information.
        public MemberController(IFormsAuthentication formsAuth, IMembershipService service)
        {
            this.FormsAuth = formsAuth ?? new FormsAuthenticationService();
            this.MembershipService = service ?? new AccountMembershipService();
        }

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }

        public IMembershipService MembershipService
        {
            get;
            private set;
        }

        public ActionResult Login()
        {
            return this.View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public ActionResult Login(string txtUsername, string txtPassword, string hidRemember)
        {
            string userName = txtUsername.Trim();
            string password = txtPassword.Trim();
            int remember = Util.ToSafeBool(hidRemember) ? 1 : 0;
            if (!ValidateLogOn(txtUsername, txtPassword))
            {
                return new AjaxResult { ErrorMessage = "Incorrect Username or Password" };
            }
            string[] arrRoleName = new AccountMembershipService().GetRolesForUser(userName);
            if (arrRoleName.GetLength(0) == 0)
            {
                return new AjaxResult { ErrorMessage = string.Format("User {0} must belong to a Role!", userName) };
            }
            this.FormsAuth.SignIn(userName, true);
            ViewData["Username"] = userName;
            GeneralVar.gLoggedUserName = userName;
            GeneralVar.gLoggedRoleName = arrRoleName[0];
            GeneralVar.gLoggedRemember = remember;
            GeneralVar.gLoggedPassword = password;
            return this.RedirectToAction("Index", "Home");
        }
        public AjaxStoreResult GetListOrgUnit(int limit, int start, string dir, string sort)
        {
            int total =0;
            var query = new MemberDAL().GetListOrgUnit(limit, start, dir, sort, out total);
            return new AjaxStoreResult(query, total);
        }

        public ActionResult Logout()
        {
            this.FormsAuth.SignOut();
            ViewData["Username"] = string.Empty;
            return this.RedirectToAction("Login", "Desktop/Member");
        }

        public ActionResult Register()
        {

            this.ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            return this.View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(string userName, string email, string password, string confirmPassword)
        {

            this.ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;

            if (this.ValidateRegistration(userName, email, password, confirmPassword))
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(userName, password, email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    this.FormsAuth.SignIn(userName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "HomePage");
                }
                else
                {
                    this.ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return this.View();
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            this.ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return this.View("ChangePassword");
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "Exceptions result in password not being changed.")]
        public ActionResult ChangePassword(string txtCurrentPassword, string txtNewPassword, string txtConfirmPassword, string returnUrl)
        {
            string currentPassword = txtCurrentPassword.Trim();
            string newPassword = txtNewPassword.Trim();
            string confirmPassword = txtConfirmPassword.Trim();

            this.ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

            if (String.IsNullOrEmpty(currentPassword))
            {
                return new AjaxResult { ErrorMessage = "You must specify a current password" };
            }
            if (newPassword == null || newPassword.Length < MembershipService.MinPasswordLength)
            {
                return new AjaxResult { ErrorMessage = string.Format("The new password must not less than {0} characters", MembershipService.MinPasswordLength) };
            }

            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                return new AjaxResult { ErrorMessage = "The new password and confirmation password do not match." };
            }

            try
            {
                if (MembershipService.ChangePassword(User.Identity.Name, currentPassword, newPassword))
                {
                    return this.View();
                }
                else
                {
                    //this.ModelState.AddModelError("_FORM", "The current password is incorrect or the new password is invalid.");
                    return new AjaxResult { ErrorMessage = "The current password is incorrect or the new password is invalid." };
                    //return this.View();
                }
            }
            catch
            {
                return new AjaxResult { ErrorMessage = "The current password is incorrect or the new password is invalid." };
                //this.ModelState.AddModelError("_FORM", "The current password is incorrect or the new password is invalid.");
                //return this.View();
            }
        }

        public ActionResult ChangePasswordSuccess()
        {
            return this.View();
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity is WindowsIdentity)
            {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
        }

        #region Validation Methods

        private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            if (String.IsNullOrEmpty(currentPassword))
            {
                this.ModelState.AddModelError("currentPassword", "You must specify a current password.");
            }
            if (newPassword == null || newPassword.Length < MembershipService.MinPasswordLength)
            {
                this.ModelState.AddModelError("newPassword",
                    String.Format(CultureInfo.CurrentCulture,
                         "You must specify a new password of {0} or more characters.",
                         MembershipService.MinPasswordLength));
            }

            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                this.ModelState.AddModelError("_FORM", "The new password and confirmation password do not match.");
            }

            return this.ModelState.IsValid;
        }

        private bool ValidateLogOn(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName))
            {
                this.ModelState.AddModelError("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(password))
            {
                this.ModelState.AddModelError("password", "You must specify a password.");
            }
            if (!MembershipService.ValidateUser(userName, password))
            {
                this.ModelState.AddModelError("_FORM", "The username or password provided is incorrect.");
            }
            return Membership.ValidateUser(userName, password);

            //if (Membership.ValidateUser(userName, password))
            //{
            //    //check with orgUnit
            //    return new AccountDAL().ExistUserInOrgUnit(userName, orgUnitName);
            //}


            //return this.ModelState.IsValid;
        }

        private bool ValidateRegistration(string userName, string email, string password, string confirmPassword)
        {
            if (String.IsNullOrEmpty(userName))
            {
                this.ModelState.AddModelError("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(email))
            {
                this.ModelState.AddModelError("email", "You must specify an email address.");
            }
            if (password == null || password.Length < MembershipService.MinPasswordLength)
            {
                this.ModelState.AddModelError("password",
                    String.Format(CultureInfo.CurrentCulture,
                         "You must specify a password of {0} or more characters.",
                         MembershipService.MinPasswordLength));
            }
            if (!String.Equals(password, confirmPassword, StringComparison.Ordinal))
            {
                this.ModelState.AddModelError("_FORM", "The new password and confirmation password do not match.");
            }
            return this.ModelState.IsValid;
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication this.provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion



        public AjaxStoreResult GetListRole(int limit, int start, string dir, string sort)
        {
            AccountMembershipService accountMembershipService = new AccountMembershipService();
            try
            {
                string[] listRole = Roles.GetAllRoles();
                int total = listRole.GetLength(0);
                List<Role> listMembershipRole = new List<Role>();

                for (int i = start; i < start + limit && i < total  ; i++)
                {
                    string roleName = listRole[i];
                    listMembershipRole.Add(new Role { Name = roleName });
                }
                return new AjaxStoreResult(listMembershipRole, total);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public AjaxStoreResult GetListRoleNotInUser(string userName)
        {
            int total = 0;
            List<Role> listRole = new Role().GetListRoleNotInUser(0, 0, out total, userName);
            List<UserAndRole> listUserAndRole = new List<UserAndRole>();
            foreach (Role role in listRole)
            {
                listUserAndRole.Add(new UserAndRole {  RoleId = role.RoleId, UserName = userName, RoleName = role.Name });
            }
            return new AjaxStoreResult(listUserAndRole, total);
        }

        public AjaxStoreResult GetListUserNotInRole(string roleName)
        {
            int total = 0;
            List<User> listUser = new User().GetListUserNotInRole(0, 0, out total, roleName);
            List<UserAndRole> listUserAndRole = new List<UserAndRole>();
            foreach (User user in listUser)
            {
                listUserAndRole.Add(new UserAndRole { RoleName = roleName, UserId = user.UserId, UserName = user.Name, Email = user.Email });
            }
            return new AjaxStoreResult(listUserAndRole, total);
        }

        public AjaxStoreResult GetListUser(int limit, int start, string dir, string sort)
        {
            AccountMembershipService accountMembershipService = new AccountMembershipService();
            try
            {
                int total = 0;
                //int pageIndex = (start + limit) / limit - 1;
                List<User> listUser = new User().GetListUser(limit,start, out total);
                return new AjaxStoreResult(listUser, total);
            }
            catch (Exception)
            {
                throw;
            }
        }
        
        public AjaxStoreResult GetUser(int limit, int start, string dir, string sort)
        {
            AccountMembershipService accountMembershipService = new AccountMembershipService();
            try
            {
                int total = 0;
                int pageIndex = (start + limit) / limit - 1;
                List<User> listUser = new User().GetListUser(pageIndex, limit, out total);
                return new AjaxStoreResult(listUser, total);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public AjaxStoreResult SaveRoles()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);
            try
            {
                string jsonData = HttpContext.Request["data"];
                StoreDataHandler dataHandler = new StoreDataHandler(jsonData);
                ChangeRecords<Role> data = dataHandler.ObjectData<Role>();
                AccountMembershipService accountMembershipService = new AccountMembershipService();
                foreach (Role membershipRole in data.Deleted)
                {
                    accountMembershipService.DeleteRole(membershipRole.Name);
                    //delete corresponding features
                    new PermissionDAL().DeleteFeatureRole(membershipRole.Name);
                }
                foreach (Role membershipRole in data.Created)
                {
                    if (!string.IsNullOrEmpty(membershipRole.Name))
                    {
                        if (Roles.RoleExists(membershipRole.Name))
                            throw new Exception("Role Name existed!");

                        accountMembershipService.CreateRole(membershipRole.Name);
                        //create corresponding features
                        new PermissionDAL().GenerateFeatureRole(membershipRole.Name, "...");
                    }
                }
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }

        public AjaxStoreResult SaveUserInRole()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);
            try
            {
                string jsonData = HttpContext.Request["data"];
                StoreDataHandler dataHandler = new StoreDataHandler(jsonData);
                ChangeRecords<UserInRole> data = dataHandler.ObjectData<UserInRole>();
                AccountMembershipService accountMembershipService = new AccountMembershipService();
                List<string> listUser = new List<string>();
                string roleName = string.Empty;
                foreach (UserInRole userInRole in data.Deleted)
                {
                    roleName = userInRole.RoleName;
                    listUser.Add(userInRole.UserName);
                }
                if (!string.IsNullOrEmpty(roleName))
                {
                    string[] arrUserName = listUser.ToArray();
                    new AccountMembershipService().RemoveUsersFromRole(arrUserName, roleName);
                }
                return ajaxStoreResult;
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }

        public AjaxStoreResult SaveUsers()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);
            try
            {
                string jsonData = HttpContext.Request["data"];
                StoreDataHandler dataHandler = new StoreDataHandler(jsonData);
                ChangeRecords<User> data = dataHandler.ObjectData<User>();
                AccountMembershipService accountMembershipService = new AccountMembershipService();
                foreach (User membershipUser in data.Deleted)
                {
                    accountMembershipService.DeleteUser(membershipUser.Name);
                }
                foreach (User membershipUser in data.Created)
                {
                    if (!string.IsNullOrEmpty(membershipUser.Name))
                    {
                        if (Roles.RoleExists(membershipUser.Name))
                            throw new Exception("User Name existed!");

                        accountMembershipService.CreateUser(membershipUser.Name, GeneralConstant.DEFAULT_USER_PASSWORD, membershipUser.Email);
                    }
                }
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }

        public AjaxStoreResult GetListUserInRole(int limit, int start, string roleName)
        {
            try
            {
                if (string.IsNullOrEmpty(roleName))
                    return new AjaxStoreResult(new List<User>(), 0);

                int total = 0;
                List<User> listUser = new User().GetListUser(start, limit, out total, roleName);
                if (listUser == null  || listUser.Count == 0)
                    return new AjaxStoreResult(new List<User>(), 0);

                List<UserAndRole> listUserAndRole = new List<UserAndRole>();
                foreach (User user in listUser)
                {
                    listUserAndRole.Add(new UserAndRole { RoleName = roleName, UserId = user.UserId, UserName = user.Name, Email = user.Email });
                }
                return new AjaxStoreResult(listUserAndRole, total);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public AjaxStoreResult GetListRoleInUser(int limit, int start, string userName)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    return new AjaxStoreResult(new List<Role>(), 0);

                int total = 0;
                //int pageIndex = (start + limit) / limit - 1;
                List<Role> listRole = new Role().GetListRole(start, limit, out total, userName);

                List<UserAndRole> listUserAndRole = new List<UserAndRole>();
                foreach (Role role in listRole)
                {
                    listUserAndRole.Add(new UserAndRole { RoleName =  role.Name, UserName = userName});
                }
                //List<UserInRole> listUserInRole = new UserInRole().GetListUserInRole(pageIndex, limit, out total, roleName);
                //return new AjaxStoreResult(listUser, total);
                return new AjaxStoreResult(listUserAndRole, total);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public AjaxStoreResult SaveUserInRoles()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);
            try
            {
                string jsonData = HttpContext.Request["data"];
                StoreDataHandler dataHandler = new StoreDataHandler(jsonData);
                ChangeRecords<UserAndRole> data = dataHandler.ObjectData<UserAndRole>();
                AccountMembershipService accountMembershipService = new AccountMembershipService();
                List<string> listUser = new List<string>();
                string roleName = string.Empty;
                //delete
                listUser = new List<string>();
                foreach (UserAndRole userAndRole in data.Deleted)
                {
                    roleName = userAndRole.RoleName;
                    listUser.Add(userAndRole.UserName);
                }
                if (!string.IsNullOrEmpty(roleName))
                {
                    string[] arrUserName = listUser.ToArray();
                    new AccountMembershipService().RemoveUsersFromRole(arrUserName, roleName);
                }

                //add
                listUser = new List<string>();
                foreach (UserAndRole userAndRole in data.Updated)
                {
                    roleName = userAndRole.RoleName;
                    listUser.Add(userAndRole.UserName);
                }
                if (!string.IsNullOrEmpty(roleName))
                {
                    string[] arrUserName = listUser.ToArray();
                    new AccountMembershipService().AddUsersToRole(arrUserName, roleName);
                }


                return ajaxStoreResult;
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }

        public AjaxStoreResult SaveRoleInUsers()
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);
            try
            {
                string jsonData = HttpContext.Request["data"];
                StoreDataHandler dataHandler = new StoreDataHandler(jsonData);
                ChangeRecords<UserAndRole> data = dataHandler.ObjectData<UserAndRole>();
                AccountMembershipService accountMembershipService = new AccountMembershipService();
                List<string> listRole = new List<string>();
                string UserName = string.Empty;
                //delete
                listRole = new List<string>();
                foreach (UserAndRole UserAndRole in data.Deleted)
                {
                    UserName = UserAndRole.UserName;
                    listRole.Add(UserAndRole.RoleName);
                }
                if (!string.IsNullOrEmpty(UserName))
                {
                    string[] arrRoleName = listRole.ToArray();
                    new AccountMembershipService().RemoveUserFromRoles(UserName,arrRoleName);
                }

                //add
                listRole = new List<string>();
                foreach (UserAndRole UserAndRole in data.Updated)
                {
                    UserName = UserAndRole.UserName;
                    listRole.Add(UserAndRole.RoleName);
                }
                if (!string.IsNullOrEmpty(UserName))
                {
                    string[] arrRoleName = listRole.ToArray();
                    new AccountMembershipService().AddUserToRoles(UserName,arrRoleName);
                }


                return ajaxStoreResult;
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success = false;
                ajaxStoreResult.SaveResponse.Message = e.Message;
            }

            return ajaxStoreResult;
        }


    }
}